<script setup lang="ts">
import type { TableProps } from 'ant-design-vue'

import { ref, watch } from 'vue'

import { useVbenModal } from '@vben/common-ui'

import { Button, message, Popconfirm, Switch, Table } from 'ant-design-vue'

import { exportMaterialBill, getSendMaterialData } from '#/api/spuBom'

import SendMaterial_info from './SendMaterial_info.vue'

// 定义组件props并获取props引用
const props = defineProps<{
  data: any
}>()

const NeedPurchaseList = ref([])

const show_factory_diff = ref(false)

// 监听data变化，更新表格数据
watch(
  () => props.data,
  (newData) => {
    if (newData) {
      initData(props.data.id)
    }
  },
  { immediate: true },
)

const baseColumns = [
  {
    title: 'BOM类型',
    dataIndex: 'bom_name',
    key: 'bom_name',
    align: 'center',
    resizable: true,
    ellipsis: true,
  },
  {
    title: '预计用量',
    dataIndex: 'single_piece',
    key: 'single_piece',
    align: 'center',
    resizable: true,
    ellipsis: true,
    width: 80,
  },
  {
    title: '唛架用量',
    dataIndex: 'marker_single_piece',
    key: 'marker_single_piece',
    align: 'center',
    width: 80,
    resizable: true,
  },
  {
    title: '实际面料',
    children: [
      {
        title: '面料名称',
        dataIndex: 'material_name',
        key: 'material_name',
        align: 'center',
        width: 200,
        ellipsis: true,
        resizable: true,
      },
      {
        title: '单价',
        dataIndex: 'price',
        key: 'price',
        align: 'center',
        resizable: true,

      },
      {
        title: '单位',
        dataIndex: 'unit',
        key: 'unit',
        align: 'center',
        resizable: true,
        width: 50,
      },
    ],
  },
  {
    title: '算料件数',
    dataIndex: 'computedNum',
    key: 'computedNum',
    align: 'center',
    resizable: true,
  },
  {
    title: '裁床数',
    dataIndex: 'cutedNum',
    key: 'cutedNum',
    align: 'center',
    resizable: true,
  },
  {
    title: '完结入库数',
    dataIndex: 'in_stock_num2',
    key: 'in_stock_num2',
    align: 'center',
    resizable: true,
  },
  {
    title: '下单数量',
    dataIndex: 'purchase_num',
    key: 'purchase_num',
    align: 'center',
    resizable: true,
  },
  {
    title: '已收数量',
    dataIndex: 'reviced_num',
    key: 'reviced_num',
    align: 'center',
    resizable: true,
  },
]

// show_factory_diff为true时显示的列
const factoryDiffColumns = [
  {
    title: '含损耗发料需求数',
    dataIndex: 'two_need_num',
    key: 'two_need_num',
    align: 'center',
    resizable: true,
  },
  {
    title: '实发数量',
    dataIndex: 'send_num',
    key: 'send_num',
    align: 'center',
    resizable: true,
  },
  {
    title: '含损耗发料差异数',
    dataIndex: 'two_send_need_diff_num',
    key: 'two_send_need_diff_num',
    align: 'center',
    resizable: true,
  },
  {
    title: '含损耗发料差异金额',
    dataIndex: 'two_send_need_diff_price',
    key: 'two_send_need_diff_price',
    align: 'center',
    resizable: true,
  },
]

// show_factory_diff为false时显示的列
const normalColumns = [
  {
    title: '发料需求数',
    dataIndex: 'need_num',
    key: 'need_num',
    align: 'center',
    resizable: true,
  },
  {
    title: '实发数量',
    dataIndex: 'send_num',
    key: 'send_num',
    align: 'center',
    resizable: true,
  },
  {
    title: '发料差异数',
    dataIndex: 'send_need_diff_num',
    key: 'send_need_diff_num',
    align: 'center',
    resizable: true,
  },
  {
    title: '发料差异金额',
    dataIndex: 'send_need_diff_price',
    key: 'send_need_diff_price',
    align: 'center',
    resizable: true,
  },
]

const addColumns = [
  {
    title: '发料明细',
    dataIndex: 'send_table_dates',
    key: 'send_table_dates',
    align: 'center',
    resizable: true,
  },
  {
    title: '未发数量',
    dataIndex: 'no_send_num',
    key: 'two_send_need_diff_price',
    align: 'center',
    resizable: true,
  },
]

// 动态生成columns数组，根据show_factory_diff条件组合不同列
// const columns: any = computed(() => {
//   // 基础列 + 已收数量列（始终显示）
//   const baseWithReceived = [...baseColumns];
//
//   if (show_factory_diff.value) {
//     // 工厂差异模式：基础列 + 已收数量列 + 工厂差异列
//     return [...baseWithReceived, ...factoryDiffColumns, ...addColumns];
//   } else {
//     // 普通模式：基础列 + 已收数量列 + 普通列
//     return [...baseWithReceived, ...normalColumns, ...addColumns];
//   }
// });
const columns = ref([...baseColumns,...normalColumns, ...addColumns])
watch(show_factory_diff, (newData) => {
  if (newData) {
    // 工厂差异模式：基础列 + 已收数量列 + 工厂差异列
    columns.value = [...baseColumns, ...factoryDiffColumns, ...addColumns]
  } else {
    // 普通模式：基础列 + 已收数量列 + 普通列
    columns.value = [...baseColumns, ...normalColumns, ...addColumns]
  }
})

const columns1: any = ref([
  {
    title: 'BOM类型',
    dataIndex: 'bom_name',
    key: 'bom_name',
    align: 'center',
    width: 200,
    resizable: true,
    ellipsis: true,
  },
  {
    title: '实际面料',
    resizable: true,
    children: [
      {
        title: '面料名称',
        dataIndex: 'material_name',
        key: 'material_name',
        align: 'center',
        width: 200,
        resizable: true,
      },

      {
        title: '单价',
        dataIndex: 'price',
        key: 'price',
        align: 'center',
        resizable: true,
      },
      {
        title: '单位',
        dataIndex: 'unit',
        key: 'unit',
        align: 'center',
        resizable: true,
      },
    ],
  },

  {
    title: '需求量（系统）',
    dataIndex: 'need_num',
    key: 'need_num',
    align: 'center',
    resizable: true,
  },
  {
    title: '已收数量',
    dataIndex: 'reviced_num',
    key: 'reviced_num',
    align: 'center',
    resizable: true,
  },
  {
    title: '已发数量',
    dataIndex: 'send_num',
    key: 'send_num',
    align: 'center',
    resizable: true,
  },
  {
    title: '未发/配置数量',
    dataIndex: 'num',
    key: 'num',
    align: 'center',
    resizable: true,
  },
])

function initData(id: any) {
  const param = {
    bomId: id,
  }
  getSendMaterialData(param).then((response) => {
    NeedPurchaseList.value = response.data.data.list
  })
}

function refresh() {
  initData(props.data.id)
}

const selectRows: any = ref([])
const rowSelect: TableProps['rowSelection'] = {
  onChange: (selectedRowKeys: any, selectedRows: any) => {
    // 将no_send_num转换为num
    const transformedRows = selectedRows.map((row) => ({
      ...row,
      num: row.no_send_num,
    }))
    selectRows.value = transformedRows
    console.log(`选择key有哪些: ${selectedRowKeys}`, '选中的行数据有哪些:', transformedRows)
  },
}

function placeOrder() {
  if (selectRows.value.length > 0) {
    SendMaterial_infoModalApi.setData({
      data: selectRows.value,
      id: props.data.id,
      purchase_id: props.data.purchase_id,
    }).open()
  } else {
    message.error('请选择面料')
  }
}

const [SendMaterial_infoModal, SendMaterial_infoModalApi] = useVbenModal({
  connectedComponent: SendMaterial_info,
})

function exportMaterial() {
  exportMaterialBill({
    bomId: props.data.id,
    show_factory_diff: show_factory_diff.value,
  }).then((res) => {
    let url = ''
    url = res.data === undefined ? URL.createObjectURL(res) : URL.createObjectURL(res.data)
    const dom = document.createElement('a')
    dom.setAttribute('href', url)
    dom.setAttribute('download', '物料发料情况.xlsx')
    dom.click()
    dom.click()
    // 下载完成后清理
    setTimeout(() => {
      dom.remove()
      window.URL.revokeObjectURL(url)
      message.success('下载成功')
    }, 100)
  })
}

const sendTableRowClassName = (record) => {
  if (record.two_send_need_diff_num < 0 && show_factory_diff.value) {
    return 'red-text-row'
  }
  if (record.send_need_diff_num < 0 && !show_factory_diff.value) {
    return 'red-text-row'
  }
}
</script>

<template>
  <div style="width: 100%; display: flex; justify-content: flex-end; margin-bottom: 10px">
    <Popconfirm title="确定导出单款物料报表" ok-text="确认" cancel-text="取消" @confirm="exportMaterial()">
      <Button type="primary" style="margin-right: 100px"> 导出单款物料报表 </Button>
    </Popconfirm>

    <div style="margin-right: 100px">
      按损耗显示
      <Switch v-model:checked="show_factory_diff" />
    </div>
    <strong style="font-size: 18px">应发料 :</strong>
  </div>
  <Table
    class="w-full mb-2"
    :scroll="{ x: '100%', y: 'calc(20vh)' }"
    row-key="id"
    :row-selection="rowSelect"
    bordered
    :data-source="NeedPurchaseList"
    :columns="columns"
    :pagination="false"
    size="small"
    :row-class-name="sendTableRowClassName"
    @resize-column="(w: any, col: any) => (col.width = w)"
  />
  <div style="width: 100%; display: flex; justify-content: flex-end; font-size: 18px">
    <strong>已选 :</strong>
  </div>

  <Table class="w-fill" bordered :scroll="{ x: '100%', y: 'calc(25vh)' }" :data-source="selectRows" :columns="columns1" :pagination="false" size="small" @resize-column="(w: any, col: any) => (col.width = w)" />
  <div style="width: 100%; display: flex; justify-content: flex-end; font-size: 18px">
    <Button type="primary" @click="placeOrder()">去发料</Button>
  </div>
  <SendMaterial_infoModal @refresh="refresh()" />
</template>

<style scoped>
:deep(.red-text-row) {
  color: red !important;
}

/* 确保表格单元格中的文本也应用红色 */
:deep(.red-text-row td) {
  color: red !important;
}

/* 确保表格内容中的所有文本元素都应用红色 */
:deep(.red-text-row span),
:deep(.red-text-row div),
:deep(.red-text-row u) {
  color: red !important;
}
</style>
